package com.lse_api.config.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lse_api.entity.Token;
import com.lse_api.service.TokenService;
import com.lse_api.utils.ReturnMsg;
import com.lse_api.utils.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户token验证
 *
 * @author 祁雪
 */
@Component
@Slf4j
public class UserInterceptorConfig implements HandlerInterceptor, ReturnMsg {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 读取token
        String info = request.getHeader("user_key");

        boolean flag = false;

        try {
            response.setContentType("application/json; charset=utf-8");

            ObjectMapper mapper = new ObjectMapper();

            if (StringUtils.isEmpty(info)) {
                flag = false;

                response.getWriter().println(mapper.writeValueAsString(Status.error(TOKEN_IS_NULL)));

                return flag;
            }

            // 查询token
            QueryWrapper<Token> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("info", info);
            Token token = tokenService.getOne(tokenQueryWrapper);
            if (token == null) {
                flag = false;

                response.getWriter().println(mapper.writeValueAsString(Status.error(TOKEN_READ_IS_NULL)));

                return flag;
            }

            flag = true;
            request.setAttribute("token", token);
            return flag;

        } catch (Exception e) {
            log.error("token read out error", e);
        }

        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
